﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IGolovkine.AoA.Diagnostics;

namespace IGolovkine.AoA.Tcp
{
    public class MessageAggregator
    {
        private readonly Subject<Message> _input;
        private readonly object _syncLock = new object();

        private readonly Queue<Message> _messages;
        private ILogger _logger;

        private DateTime _lastMessage = DateTime.Now;

        public MessageAggregator()
        {
            _logger = ApplicationContext.LogManager.GetClassLogger(this);

            _input = new Subject<Message>();
            _input.Subscribe(this.Add);
            _messages = new Queue<Message>();
        }

        public IObserver<Message> Input
        {
            get { return _input; }
        }


        public DateTime LastMessage
        {
            get { return _lastMessage; }
        }

        private void Add(Message message)
        {
            _logger.Trace("{0} enqueued", _messages.Count);
            lock (_syncLock)
            {
                _messages.Enqueue(message);
                _lastMessage = DateTime.Now;
            }
        }
        
        public Message[] Dequeue(int maxDataLength)
        {
            _logger.Trace( "Dequeuing messages, max data length = {0}", maxDataLength); 
            lock (_syncLock)
            {
                var result = _messages.ToArray();
                _messages.Clear();
                return result;
            }
        }

        public int Count
        {
            get
            {
                lock (_syncLock)
                {
                    return _messages.Count;
                }
            }
        }

        public Message[] DequeueAll()
        {
            return this.Dequeue(int.MaxValue);
        }
    }
}
